package basic;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import utils.DateUtil;
import utils.StringUtil;

public class BaseEntity implements Serializable {

	private static final long serialVersionUID = 1L;
	public static Set<String> EXCLUDE = Collections.synchronizedSet(new HashSet<String>());
	static {
		EXCLUDE.add("serialVersionUID");
	}

	public String toString() {
		StringBuffer sb = new StringBuffer();
		for (Field field : this.getClass().getDeclaredFields()) {
			if (EXCLUDE.contains(field.getName())) {
				continue;
			}
			try {
				field.setAccessible(true);
				if (field.getType() == Date.class) {
					sb.append(field.getAnnotation(FieldMeta.class).name() + "[" + field.getName() + "] : " + DateUtil.format((Date) field.get(this)) + System.lineSeparator());
				} else {
					sb.append(field.getAnnotation(FieldMeta.class).name() + "[" + field.getName() + "] : " + field.get(this) + System.lineSeparator());
				}
			} catch (Exception e) {
				continue;
			}
		}
		return sb.toString();
	}

	public String toJson() {
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		for (Field field : this.getClass().getDeclaredFields()) {
			if (EXCLUDE.contains(field.getName())) {
				continue;
			}
			try {
				field.setAccessible(true);
				if (field.get(this) == null) {
					sb.append("\"" + field.getName() + "\":\"\",");
				} else {
					if (field.getType() == Date.class) {
						sb.append("\"" + field.getName() + "\":\"" + DateUtil.format((Date) field.get(this)) + "\",");
					} else {
						sb.append("\"" + field.getName() + "\":\"" + field.get(this) + "\",");
					}
				}
			} catch (Exception e) {
				continue;
			}
		}
		return StringUtil.removeLast(sb.toString(), ",") + "}";
	}

}
